import os
import  shutil
# 只获取最底层的字文件路径
def get_subfolder_paths(root_dir, crop_path = '100-images'):
    subfolder_paths = []
    for dirpath, dirnames, filenames in os.walk(root_dir):
        if not dirnames:
            full_path = os.path.abspath(dirpath)
            # 对绝对路径进行裁剪
            split_path = full_path.split(crop_path)[1]
            subfolder_paths.append(split_path)

    return subfolder_paths

def get_img_file_name(path):
    file_names = []
    for root, dirs, files in os.walk(path):
        for file in files:
            if file.lower().endswith('.jpg'):
                file_name = os.path.splitext(file)[0]
                file_names.append(file_name)
    return file_names


'''
    按照A路径下的文件名称，从B路径下拷贝想要的文件到A路径下
'''
if __name__ == '__main__':
    tmp_name = '102-images'
    # 获取子目录的路径
    root = "/home/yjh_test/data/helmet_data/HelmetDataset-zhengshu-20241121/" + tmp_name
    crop_path = tmp_name
    sub_path_names = get_subfolder_paths(root, crop_path)
    # 测试
    # for path in sub_path_names:
    #     print(path)
    # exit(0)
    # A路径
    A_path = '/home/yjh_test/data/helmet_data/HelmetDataset-zhengshu-20241121/'+ tmp_name
    # B路径
    B_path = '/home/yjh_test/data/HelmetDataset-zhengshu-20241121-json/' + tmp_name
    # 丢失路径保存到txt中
    txt_path = '102.txt'
    if os.path.exists(txt_path):
        # 如果存在，清空文件内容
        open(txt_path, 'w').close()

    for tmp_path in sub_path_names:
        A_path_1 = A_path + tmp_path
        B_path_1 = B_path + tmp_path
        file_names = get_img_file_name(A_path_1)
        # 如果需要搬用的不是json 就在下面改
        number = 0
        for name in file_names:
            B_path_2 = os.path.join(B_path_1, name + '.json')
            if os.path.exists(B_path_2):
                # print(B_path_2)
                number += 1
                shutil.copy(B_path_2, A_path_1)
            else:
                print("file {} is empty !!!".format(B_path_2))
                with open(txt_path, 'a') as txt_file:
                    txt_file.write(B_path_2 + '\n')
        # exit(0)
        print("path:{} copy numbers {} !".format(B_path_1, number))
    print("finish all copy !!")



